/**
 * 组件加载示例：
 * 
 * <mfc-workspace dir="meeting-detail">
              <v3 
              v2Comps={[vm.$v2Comps()]}
              comp="meeting-detail-phase-gate-review" state={{text,record,index}} vm={this}></v3>
            </mfc-workspace>
 * 
 */


let bizConfig = window.$v3.bizConfig;

let globalComponentsLoaderName = bizConfig.globalComponentsLoaderName;
let dir = bizConfig.esmJsDir;
let loadScriptJsDir = bizConfig.loadScriptJsDir;

let routerPageContainerSelector = bizConfig.routerPageContainerSelector

let nextTick=()=>{
  return new Promise((resolve)=>{
    setTimeout(()=>{
      resolve()
    })
  })
}

// let store = require("./v3.store.js").default;
import { store, v3BootstrapPromiseFn, ready } from "./mfc-init.js";
// import { flyPageByLocationPath } from './mfc-init.js'
if (location.hostname == "127.0.0.1") {
  window.$$store = store;
}
// import parse from "./mfcParser.js";
import parseMFC, { generateNewPathByRelativePath,DOT_MFC_POSTFIX } from "./mfcParser.js";

let hasUILibrary = false;

let isGlobalComponentsRegistered = false;
let allowReloadCompForHMR = {}

let loadMfcDepsPromiseResolver;
let loadMfcDepsPromise = new Promise((resolve) => {
  loadMfcDepsPromiseResolver = resolve;
})

let isHmrPushState=false;
let loadMfcAppEntryCompPromiseResolver;
let loadMfcAppEntryCompPromise;
let isFirstLoadMfcAppEntryCompPromiseResolved=false;
// alert(window.$v3.$utils.isDevServer())
// if(window.$v3.$utils.isDevServer()){
//   window.loadMfcAppEntryCompPromise=loadMfcAppEntryCompPromise;
// }

let resetMfcAppEntryCompLoadPromise=()=>{
  loadMfcAppEntryCompPromise= new Promise((resolve) => {
    loadMfcAppEntryCompPromiseResolver = resolve;
    if(!bizConfig.useMfcEntryComponent){
      setTimeout(()=>{
        loadMfcAppEntryCompPromiseResolver()
      },50)
    }
  })
}
resetMfcAppEntryCompLoadPromise()



let isLoadingMfcDeps = false;



export const loadMfcDeps = async function loadMfcDeps() {
  // alert(6666666)
  if (isLoadingMfcDeps) {
    // alert(5555555555)
    await loadMfcDepsPromise;
    // alert(45444)
    return;
  }


  async function loadJsFiles(){
    await window.$v3.$utils.sequenceExecPromiseArr(
      window.$v3.bizConfig
      .JS_DEPS.map((s,index) => {
        if(s.every((item)=>typeof(item)=='string')){
          let res= Promise.all(s.map(ss => window.$v3.$utils._loadJS(ss)))
          if(index<window.$v3.bizConfig.JS_DEPS.length-1){
            if(window.$v3.bizConfig.JS_DEPS[index+1].every((item)=>typeof(item)=='function')){
              res.then(()=>{
                window.$v3.bizConfig.JS_DEPS[index+1].forEach((fn)=>{
                  fn()
                })
              })
            }
          }
          
          return res;
        }
        else if(s.every((item)=>typeof(item)=='function')){
          if(index==0){
            s.forEach((fn)=>{
              fn()
            })
          }
          
          return true;
        }else{
          throw 'JS_DEPS config  must be string array of function array of every item'
        }
      })
      
      )

    // setTimeout(()=>{

    // })
    loadMfcDepsPromiseResolver()






    isLoadingMfcDeps = false;
  }

  function loadStyles(){
    return new Promise((cssResolve)=>{

      if (!hasUILibrary && !isLoadingMfcDeps) {
        
        // alert(22222)
        hasUILibrary = true;
        isLoadingMfcDeps = true;
        
        if(!window.$v3.bizConfig.CSS_DEPS.length){

          cssResolve();
          return false;
        }
        
        var head = document.getElementsByTagName('head')[0];
    
    
        window.$v3.bizConfig.CSS_DEPS.forEach((path,index) => {
          var link = document.createElement('link');
          var cssId = 'myCss-' + Math.random();  // you could encode the css path itself to generate id..
          link.id = cssId;
          link.rel = 'stylesheet';
          link.type = 'text/css';
          link.href = path;
          link.media = 'all';
          head.appendChild(link);
          if(index==window.$v3.bizConfig.CSS_DEPS.length-1){
            setTimeout(async ()=>{

              cssResolve();
              
              
            })
          }
        })
    
    
    
    
    
    
    
        
    
      }

    })

  }


  if(window.$v3.bizConfig.loadJsAndCssAtSameTime){
    loadStyles();
  }else{
    await loadStyles();
  }

  
  await loadJsFiles()

  
  // else{

  // }


}

if (window.$v3.bizConfig.loadMfcDepsWhenDocumentReady) {
  loadMfcDeps().then(async () => {
    await window.$v3.$utils.poll(window.$v3.bizConfig.watiUntil || (()=>true))
    // alert('then')
    window.$v3.bizConfig?.onReady().then(() => {
      isFirstLoadMfcAppEntryCompPromiseResolved=true;
      loadMfcAppEntryCompPromiseResolver()
    })
  })
}
let isV3BootstrapLoaded = false;
let allowInvokedHandlePushState = true;
function resizeRouterPageContainerHeight() {
  let target = document.querySelector('#mfc-page-container')
  // let target=document.querySelector(routerPageContainerSelector)
  if (target) {
    target.style.overflowY = 'scroll'
    let h = bizConfig.setRouterPageContainerHeight(window.$v3.$utils.isDevServer())
    target.style.height = h + 'px'
    target.parentNode.style.height = h + 'px'
  }

}
window.addEventListener('resize', resizeRouterPageContainerHeight)
let appendAppDiv = (target = null, id) => {
  window.$v3.doNothing('target and id--:',target,id)
  id = id || 'mfc-page-container'
  // debugger;
  return new Promise((resolve) => {
    let fn = () => {
      if(!(target instanceof HTMLElement)){
        target = document.querySelector(target || routerPageContainerSelector)
      }
      
      if (!target) {
        setTimeout(() => {
          fn();
        }, 50);
        return false;
      }
      let previouseDiv = document.querySelector('#' + id);
      window.$v3.doNothing('previouseDiv---:',previouseDiv)
      let previouseComputedStyle={

      }
      if (previouseDiv) {
        previouseComputedStyle=previouseDiv.style
        previouseDiv.parentNode.removeChild(previouseDiv)
      }
      // debugger;
      // if ($lastPage.appContainer) {
      //   $lastPage.appContainer.parentNode.removeChild($lastPage.appContainer)
      // }

      console.log('the id---',id)


      let div = document.createElement('div');
      div.id = id
      // console.log('target and dev--:',target)
      target.prepend(div);

      if(id=='mfc-page-container'){
        if (!target.style.position || target.style.position == 'initial') {
          target.style.position = 'relative';
        }
  
        
        // target.appendChild(div);
        div.style.position = "absolute";
        div.style.left = 0;
        div.style.top = 0;
        div.style.width = '100%'
        div.style.minHeight = '200px';
        // $lastPage.appContainer = div;
        resizeRouterPageContainerHeight()

      }else if(id!='mfc-app'){
        for(let i in previouseComputedStyle){
          if(!Number.isInteger(i-0) && i!='cssText' && typeof(previouseComputedStyle[i])=='string'){
            // console.log('i----:',i,previouseComputedStyle[i])
            div.style[i]=previouseComputedStyle[i]
          }
        }

      }

      
      resolve(div)
    }
    setTimeout(fn,50)
    // fn()

  })








}
let HMRdebounceFlag=true;
let $tArr=[]
let methods = {

  handlePushState: async function (nextUrl, workspaceDir = undefined, isAppEntryComp = false,forceReloadComp=false) {
    
    // alert(workspaceDir)

    
    if (!allowInvokedHandlePushState) {
      return false;
    }
    if (window.$v3.bizConfig.isProductionDebugMode()) {
      console.trace()
    }

    if (!window.$v3.$utils.isDevServer()) {
      allowInvokedHandlePushState = false;
    }


    setTimeout(() => {
      allowInvokedHandlePushState = true;
    }, window.$v3.bizConfig.pushStateHandlerDebounceDuration())
    nextUrl = nextUrl || location.pathname;
    // alert('nextUrl--:'+nextUrl)
    let shouldPageAutoLoadWhenHistoryChange = !forceReloadComp?bizConfig.shouldPageAutoLoadWhenHistoryChange(nextUrl):true

    // alert(shouldPageAutoLoadWhenHistoryChange)
    // window.$v3.doNothing('shouldPageAutoLoadWhenHistoryChange--:',shouldPageAutoLoadWhenHistoryChange)

    // if(nextUrl!='mfc-app'){
    //   alert(shouldPageAutoLoadWhenHistoryChange)
    // }
    // console.log('next url and should--:',nextUrl,shouldPageAutoLoadWhenHistoryChange)
    
    if (shouldPageAutoLoadWhenHistoryChange || nextUrl=='mfc-app') {
      // if (shouldPageAutoLoadWhenHistoryChange || ifForceUsePageAutoLoad) {
      if (!isV3BootstrapLoaded) {
        await ready;
        await v3BootstrapPromiseFn();
        isV3BootstrapLoaded = true;
      }

      // return false;
      // await Promise.all([ready,v3BootstrapPromise]);
      // setTimeout(async () => {

        var path=methods.getFullPathByCompPathAndWorkspaceDirWhenLoadScript(nextUrl,workspaceDir)
        // console.log('my path---:',path)
        let compName = nextUrl.split('?')[0].split('/').reverse()[0];
        if(window.$v3.$mfcComponentsParentSelectorMap && window.$v3.$mfcComponentsParentSelectorMap[path]){
          let obj=window.$v3.$mfcComponentsParentSelectorMap[path];
          // console.log('the obj--:',obj)
          let newDiv = await appendAppDiv(obj.target, obj.id);
          // console.log('new div--:',newDiv)
          return window.$v3.$mountMfcComponent('#'+newDiv.id,
            // window.$v3.$mountMfcComponent(null,
            compName,
            obj.vm
            // // utils.getQueryString('comp'),
            // {
            //   ...window.$v3.bizConfig.providedVariablesForMfc
            // }
            , workspaceDir
            ,isAppEntryComp
            // ,
            // async () => {
  
  
  
            // }
          )
        }
        
        let targetAndIdWhenHmr = window.$v3.bizConfig?.targetAndIdWhenHmr(nextUrl, workspaceDir) || { target: null, id: null }

        let newDiv = await appendAppDiv(targetAndIdWhenHmr.target, targetAndIdWhenHmr.id);
        window.$v3.doNothing('new div--:', newDiv,targetAndIdWhenHmr.id,compName)
        
        // alert(compName)

        let idSelector=targetAndIdWhenHmr.id?('#'+targetAndIdWhenHmr.id):null
        // console.log('comp name and id selector--:',idSelector,compName)
        return window.$v3.$mountMfcComponent(idSelector,
          // window.$v3.$mountMfcComponent(null,
          compName,
          window.$v3.bizConfig.providedVariablesForMfc
          // // utils.getQueryString('comp'),
          // {
          //   ...window.$v3.bizConfig.providedVariablesForMfc
          // }
          , workspaceDir
          ,isAppEntryComp
          // ,
          // async () => {



          // }
        )
      // })

    }



  },
  // loadMfcDeps:loadMfcDeps,

  unmountV3App(vm) {
    if (!vm.$runtimeOptions) {
      return false;
    }
    // alert(1)
    // setTimeout(()=>{
    //   // setTimeout(()=>{
    //     vm.$runtimeOptions.allowUnMount=true;
    //   // })
    // },320)
    // if(!vm.$runtimeOptions.allowUnMount){
    //   return false;
    // }else{
    //   vm.$runtimeOptions.allowUnMount=false;
    // }
    if(window.$v3.$utils.isDevServer()){
      console['log']('will remove event listener')
    }
    
    document.removeEventListener("keydown", vm.$runtimeOptions.handleHMR);
    try {
      vm.$runtimeOptions.unmontV3();
      delete vm.$runtimeOptions.unmontV3;
    } catch (e) { }
  },
  async fetchGlobalComponents() {
    let config={}
    // console.log('-===================',dir + globalComponentsLoaderName, dir)
    if(globalComponentsLoaderName){
      config = await parseMFC('./mfc-src/' + globalComponentsLoaderName);
      // config = await parseMFC('./mfc-src/' + globalComponentsLoaderName, './mfc-src/');
    }
   
    // let config = await parseMFC(dir + vm.globalComponentsLoaderName, dir);

    //   config=(await Promise.all(config.$config.components.map(s=>window.$v3.$parseMFC(s)))).map(s=>({

    // [s.__path.split('/').reverse()[0].split(DOT_MFC_POSTFIX)[0]]:s
    //     }))

    // window.$v3.doNothing('config---:', config)
    window.$v3.globalComponents = config.components;
  },
  getFullPathByCompPathAndWorkspaceDirWhenLoadScript(compPath,workspaceDir){
    if (workspaceDir === undefined) {
      workspaceDir = window.$v3.bizConfig.primaryWorkspaceDir
    }
    var thisDir = loadScriptJsDir + workspaceDir + "/";
        
        var path = thisDir + compPath.split('?')[0] +DOT_MFC_POSTFIX+ "?"+(compPath.split('?')[1]||'');
        if (!path.startsWith("http://") && !path.startsWith("https://")) {
          path = path.replace(new RegExp('//','gi'),'/');
          // finalPath = finalPath.substring(1, finalPath.length);
        }    
        return path;

  },
  async mountMFCComp(elSelector, compPath, vm, workspaceDir, isAppEntryComp = false,doMount=true) {
    if(compPath!='mfc-app'){
      // console.trace()
      // console.log('//////////////////////////////////',compPath)
    }
    
    
    vm=vm||{}
    if(!window.$v3.$mfcComponentsParentSelectorMap){
      window.$v3.$mfcComponentsParentSelectorMap={

      }
    }
    
    if(compPath.split('?')[0].split('.').splice(-1)[0].split('/').reverse()[0]=='mfc-app' && !window.$v3.bizConfig.useMfcEntryComponent){
      throw 'you loaded the mfc-app file but setting biz config window.$v3.bizConfig.useMfcEntryComponent to false,expected to be true'
    }
    try{
      vm={
        ...vm
      }
    }catch(e){}
    // console.trace()
    
    if(elSelector!==null && !elSelector.startsWith('#')){
      throw 'mfc component container selector must starts with #'
    }
    window.$v3.doNothing('comp pathhhhhhhh---start----:',compPath)
    if (!isAppEntryComp) {
      await nextTick()
      
      
      //只有热更新时，以及第一次app entry promise没有resolve时候才等待
      if(isHmrPushState || !isFirstLoadMfcAppEntryCompPromiseResolved){
        await loadMfcAppEntryCompPromise;
      }
      
      
    }
    window.$v3.doNothing('comp pathhhhhhhh----end---:',compPath)

    elSelector = elSelector || '#mfc-page-container'
    window.$v3.doNothing('elSelector---',elSelector)
    // window.$v3.doNothing("thissssssssss----------:",this)


    // window.$v3.doNothing('vm in mount v3 app--:', vm)
    if (workspaceDir === undefined || workspaceDir === null) {
      workspaceDir = window.$v3.bizConfig.primaryWorkspaceDir
    }

    if (!vm.$runtimeOptions) {
      vm.$runtimeOptions = {
        // allowMount: true,
        elSelector, compPath, workspaceDir, isAppEntryComp
        , vm
        , handleHMR:(function(){

          
          return (e) =>{
            
            if(!HMRdebounceFlag){
              return false;
            }
            
            HMRdebounceFlag=false;
            setTimeout(()=>{
              HMRdebounceFlag=true;
            })
            methods.handleHMR(e, vm)
          }
        })()
      }
    }




    // v2Comps: {
    //       type: Array,
    //       default: () => [],
    //     },
    //     vm: Object,
    //     state: Object,
    //     comp: String,


    if (!document.querySelector('#app')?.__vue__) {
      if (!vm.v2Comps) { vm.v2Comps = [] }
      // if (!vm.vm) { vm.vm = {} }
      if (!vm.state) { vm.state = {} }

      if (!vm.comp) { vm.comp = compPath || 'hello-world' }
    }






    window.$v3.$parseMFC = parseMFC;

    return new Promise(async (resolve) => {

      // console.log('mmppppppp')


      // if (!vm.$runtimeOptions.allowMount) {
      //   return false;
      // }

      // vm.$runtimeOptions.allowMount = false;
      // setTimeout(() => {
      //   vm.$runtimeOptions.allowMount = true;
      // }, 1000)





      // methods.unmountV3App(vm);
      setTimeout(async () => {
        
        // window.$v3.doNothing('will add event listener')
        // vm.handleHMR=methods.handleHMR.bind(vm)
        document.addEventListener("keydown", vm.$runtimeOptions.handleHMR);
        // document.addEventListener("keydown", vm.handleHMR);
        if (!isGlobalComponentsRegistered) {
          await methods.fetchGlobalComponents();
          isGlobalComponentsRegistered = true;
          // return false;
        }

       

        var path=methods.getFullPathByCompPathAndWorkspaceDirWhenLoadScript(compPath,workspaceDir)
        // console.log('comppath and path--:',compPath,path,workspaceDir,workspaceDir.length)

        if(!window.$v3.$mfcComponentsParentSelectorMap[path]){
          window.$v3.$mfcComponentsParentSelectorMap[path]={
            id:elSelector.substring(1,elSelector.length),
            vm:vm,
            workspaceDir:workspaceDir,
            target:document.querySelector(elSelector)?.parentNode||document.body
          }
        }


        let str=path;
        let arr=str.split('://');
        if(arr.length>1){

            arr=arr.map((s,index)=>{
                // console.log(s)
                if(index==0){return s;}
                return s.split('//').join('/')
                
            })
        }
        arr=arr.join('://')
        path=arr;
        // alert(path)
        
        // let path = thisDir + vm.comp + DOT_MFC_POSTFIX;

        let exec = async () => {
          if (!window.MFC) {
            setTimeout(exec, 50);
            return false;
          } else {
            setTimeout(async () => {
              window.$v3.doNothing("path and dir--:", path, dir);

              // $v2Emit = function (key, val) {
              //               self.$emit(key, val);
              //             };
              

              let __globalMethods = {
                ...(window.$v3.bizConfig.globalProperties||{}),
                $v2RouterPush: function (path) {
                  window.$v3.$appInstance.$router.push(path);
                },

                log: function () {
                  return window.console.log.apply(window.console, arguments);
                },
                table: function () {
                  return window.console.table.apply(window.console, arguments);
                },
                alert: function (p) {
                  window.alert(p);
                },

                $v2Emit: function (key, val) {
                  self.$emit(key, val);
                },
                require: function (path) {
                  let suffix = path.toLowerCase().split(".").reverse()[0];
                  // alert(suffix)
                  let mfcFilePath = vm.$options.__path;
                  if (
                    "png jpg bmp gif pdf txt md html htm mp3 mp4 webp"
                      .split(" ")
                      .includes(suffix)
                  ) {
                    let realPath = generateNewPathByRelativePath(
                      path,
                      mfcFilePath
                    );
                    window.$v3.doNothing(
                      "mfcFilePath require mfc----:",
                      mfcFilePath,
                      path,
                      realPath
                    );
                    return realPath;
                  }
                },
              };

              // parseMFC=parseMFC.bind(this);
              let self = methods;
              // let self = this;
              self.__globalMethods = __globalMethods;
              let parseMfcWithThis = function () {
                return parseMFC.apply(self, arguments);
              };


              // console.log('path and dirrrrrrrrr:',path,dir)
              let mfcRes = await parseMfcWithThis(path, dir);
              // let mfcRes = await parseMFC(path, dir);
              // let mfcRes = await parse(path, dir);


              let Mfc = window.MFC;

              // let obj={
              //     $$store:store
              // }

              // window.$v3.doNothing('state in v3 this---:',vm.state)
              // vm.state.abc=1;
              let v2Comps = (await Promise.all(vm.v2Comps || [])).map(
                (s) => s.default
              );
              // debugger;
              // window.$v3.doNothing("mfcRes---:", mfcRes);
              let preStrFn = window.$v3.bizConfig.appTemplatePreSloter || (() => '')
              let win = window;
              mfcRes.template = window.$v3.html`<${win.$v3.bizConfig.localeProviderTag} :locale="win.$v3.bizConfig.localeProvider">`
                + (`${preStrFn(compPath,workspaceDir,isAppEntryComp,window.$v3.html) || ''}`)
                + mfcRes.template + `</${win.$v3.bizConfig.localeProviderTag}>`
              let createAppConfig={
                ...mfcRes,
                // __file:mfcRes.__path,
                // render(){
                //   return undefined;
                // },
                // onUnmounted(){
                //   setTimeout(()=>{
                //     window.$v3.$apps=window.$v3.$apps.filter(s=>s!==null)
                //   })
                // },
                beforeUnmount() {
                  let apps = window.$v3.$apps || [];

                  let instance = window.MFC.getCurrentInstance();
                  // window.$v3.doNothing('instance--:',instance)
                  // alert(instance._.uid)

                  // apps=apps.filter(s=>(s?._instance && (s?._instance?.uid !== instance._uid) ))
                  // alert(apps[0]._instance.uid)
                  // alert(vm)

                  // window.$v3.doNothing('app len---:',apps.length)
                  // alert(apps[0]._instance.uid)
                  // alert(instance._uid)
                  let index = apps.findIndex(
                    (s) => s._instance?.uid === instance.uid
                  );
                  // window.$v3.doNothing('index--:',index)
                  if (index > -1) {
                    window.$v3.$apps.splice(index, 1);
                  }

                  // window.$v3.$apps=apps;

                },
              }
              window._LAST_CREATED_MFC_APP_CONFIG=createAppConfig;
                let $ = Mfc.createApp(
                  createAppConfig
                ,
                {
                  state: vm.state,
                  vm: vm,
                  // vm: vm.vm,

                  v2Comps: v2Comps,
                }

                
              );
              if(window.$v3.bizConfig.useMfcRouter){
                let routes;
                if(typeof(window.$v3.bizConfig.mfcRouteConfig)=='function'){
                  routes=window.$v3.bizConfig.mfcRouteConfig()
                }else{
                  routes=(await window.__IMPORT(window.$v3.bizConfig.mfcRouteConfig)).default;
                }
                
                
                const router = MFCRouter.createRouter({
                  // 4. 内部提供了 history 模式的实现。为了简单起见，我们在这里使用 hash 模式。
                  history: window.$v3.bizConfig.mfcRouteMode=='history'?MFCRouter.createWebHistory():MFCRouter.createWebHashHistory(),
                  routes, // `routes: routes` 的缩写
                })
                // router.beforeEach((to,from,next)=>{
                //   console.log('route before each--:',to,from)
                //   next()
                // })

                $.use(router)

                  
              }
              window.$v3.$apps.push($);
              // let cssDirectiveCollection={

              // }
              $._cssDirectiveCollection = {};

             
              $.directive('init',{
                mounted() {
                  let config=arguments[1].value||{mounted(){},updated(){}}
                  if(typeof(config.mounted)=='function'){ config.mounted();  }
                  
                  // handleInitDirective(arguments)
                },
                updated() {
                  let config=arguments[1].value||{mounted(){},updated(){}}
                  if(typeof(config.updated)=='function'){ config.updated();  }
                  // handleInitDirective(arguments)
                },
              })


              let handleCssDirective = (args) => {
                setTimeout(() => {
                  // window.$v3.doNothing('args[0]---:',args[0],args[1])
                  // alert(JSON.stringify(args[1].value))
                  let name = Object.keys(args[1].modifiers)[0];
                  let value = args[1].value;
                  // alert(JSON.stringify(value))
                  if (name) {
                    if (!$._cssDirectiveCollection[name]) {
                      $._cssDirectiveCollection[name] = value;
                    }
                  }

                  window.$v3.doNothing(
                    "directive mounted args--:",
                    args,
                    name
                  );

                  value = $._cssDirectiveCollection[name] || value;
                  // window.$v3.doNothing('value----:',value)

                  //  let cssTextStr=''
                  for (let i in value) {
                    args[0].style[i] = value[i];
                    //  cssTextStr+=(i+':'+value[i]+';')
                  }
                  //  window.$v3.doNothing('cssTextStr--:',cssTextStr)
                  //  args[0].style.cssText=cssTextStr;
                  // window.$v3.doNothing('created args--:',args)
                });
              }

              $.directive("css", {
                beforeUnmount() {
                  window.$v3.doNothing("before unmount args--:", arguments); //
                },
                mounted() {
                  handleCssDirective(arguments)
                },
                updated() {
                  handleCssDirective(arguments)
                },
              });

              let handleReactDirective = (args) => {
                let value = args[1].value;
                // window.$v3.doNothing('value--:',value,args[0])
                if (window.ReactDom) {
                  window.$v3.tempVar = value.$options;
                  // args[0].innerHTML=''
                  ReactDOM.unmountComponentAtNode(args[0])
                  window.ReactDom?.render(value.comp, args[0]);
                }

                // window.$v3.doNothing('arguments of react---:',arguments)
              }

              $.directive('react', {
                beforeUnmount() {
                  //这里干销毁react组件的事儿
                },
                updated() {
                  handleReactDirective(arguments)
                },
                beforeUnmount(){
                  ReactDOM.unmountComponentAtNode(arguments[0])
                },
                mounted() {
                  handleReactDirective(arguments)
                },
              })

              for (let i in __globalMethods) {
                // if (!"require".split(" ").includes(i)) {
                $.config.globalProperties[i] = function () {
                  return __globalMethods[i].apply(this, arguments);
                };
                // }
              }

              $.config.globalProperties.win = window;
              $.config.globalProperties.isLoadingApp$ = window.MFC.ref(true);
              $.config.globalProperties.$store=window.$v3.$store;
              // $.config.globalProperties.$t=window.MFC.reactive({
              //   lang:'zh-cn'
              // })
              
             
              window.$$t.switchLanguage=(key)=>{
                window.$$t.lang=key;
                if($tArr.length){
                  $tArr.forEach(($t)=>{
                    let obj=window.$$t.config[key]
                    // debugger;
                    for(let i in obj){
                      $t[i]=obj[i]
                    }
                    // $t.value= obj;
                  })
                  
                }
                // else{
                  return JSON.parse(JSON.stringify(window.$$t.config[key]))
                // }
                
              };
              $.config.globalProperties.$switchLanguage=window.$$t.switchLanguage
              $.config.globalProperties.$t=window.MFC.reactive(window.$$t.switchLanguage('zh-cn'))
              $tArr.push($.config.globalProperties.$t)
              // window.$$t.$t=$t;
              // for(let i in $.config.globalProperties){
              //   if(typeof($.config.globalProperties[i])=='function'){
              //     __globalMethods[i]=$.config.globalProperties[i]
              //   }
              // }
              window.$v3.bizConfig.UI_LIB_DEFINER($)

              let obj = window.$v3.globalComponents;

              for (let i in obj) {
                let o = obj[i];
                // window.$v3.doNothing('o---:', o)
                $.component(i, o);
              }

              vm.$runtimeOptions.unmontV3 = $.unmount;

              // window.$v3.doNothing('elSelector---:',elSelector)
              // console.log('$---------:',$,elSelector)
              // console.log('el selector---:',document.querySelector(elSelector))
              if(doMount){
                $.mount(elSelector);
              }
              

              // let res = $.mount(vm.elSelector);
              // window.$v3.doNothing("resssssssssssss-----------", $);
              vm.$mfcAppInstance = $;
              resolve($)
            });
          }
        };

        exec();
      })
    })



  },
  async handleHMR(e, vm) {
    let tStart=Date.now()

    let compPath = vm.$runtimeOptions.compPath
    window.$v3.doNothing('compPath----:', compPath)
    // if (compPath == 'mfc-app') {
      resetMfcAppEntryCompLoadPromise();
      // loadMfcAppEntryCompPromise = new Promise((resolve) => {
      //   loadMfcAppEntryCompPromiseResolver = resolve;
      // })
    // }
    // if('mfc-app'==vm.$runtimeOptions.compPath){
    //   return false;
    // }

    if (location.hostname != "127.0.0.1" && location.hostname != "localhost") {
      return false;
    }

    // window.$v3.doNothing('e.keyCode',e.keyCode,e.ctrlKey,e.altKey,e.keyCode)

    // window.$v3.doNothing('e and key code---:',e,e.keyCode)
    if (e.ctrlKey && e.altKey && (e.keyCode == 17 || e.keyCode == 18)) {
      
      // window.$v3.doNothing('e.shiftKey--:', e.keyCode, e.shiftKey)

      // alert(e.shiftKey)
      // window.$v3.doNothing(1)
      // // window.$v3.doNothing('1')
      // if(e.keyCode!=17 && e.keyCode!=18 ){
      //     return false;
      // }
      // if (!vm.$runtimeOptions.allowMount) {
      if (allowReloadCompForHMR[compPath] === false) {
        return false;
      }

      // alert('123')

      // vm.$runtimeOptions.allowMount = false;
      allowReloadCompForHMR[compPath] = false;
      setTimeout(() => {
        // vm.$runtimeOptions.allowMount = true;
        allowReloadCompForHMR[compPath] = true;
      }, 2000);


      for (let i in window.$v3.mfcFileCaches) {
        delete window.$v3.mfcFileCaches[i]
      }




      window.$v3.$bus.$emit("B_HMR");

      // window.$v3.doNothing('this in handleHMR', this, methods)

      // if(e.shiftKey){

      // }

      console['lo'+'g']('will remount--:',vm.$runtimeOptions.compPath)
      isHmrPushState=true;
      await methods.handlePushState(vm.$runtimeOptions.compPath, 
        vm.$runtimeOptions.workspaceDir, 
        vm.$runtimeOptions.isAppEntryComp,true)
      
      if (compPath == 'mfc-app'){
        loadMfcAppEntryCompPromiseResolver()
      }
      isHmrPushState=false;
      setTimeout(()=>{
        window.eval(`console.log('%c [HMR RELOAD USED TIME:${Date.now()-tStart}]','color:#0f0;')`)
      })
      
      // flyPageByLocationPath(null,vm.$runtimeOptions.compPath)
      // flyPageByLocationPath(null,true,vm.$runtimeOptions.compPath)
      // setTimeout(() => {
      //   // methods.unmountV3App(vm);
      //   window.$v3.doNothing('vm--:', vm)
      //   setTimeout(() => {

      //     // console.clear();
      //     methods.mountMFCComp(vm.$runtimeOptions.elSelector, vm.$runtimeOptions.compPath, vm, vm.$runtimeOptions.workspaceDir);
      //   })
      //   // },300)

      // });
    }
  },

}


export default methods;